<template>
  <div class="oe-sub-manage" v-loading="loading">
    <top-tip :title="title" :showBack="false"></top-tip>
    <div class="oe-manage-search">
      <!-- <span class="oe-manage-text">院系名称/编码：</span> -->
     
        <span class="oe-manage-input">
        <a-input placeholder="请输入院系名称/编码" v-model="key">
          <template #prefix>
            <span class="iconfont icon-sousuo"></span>
          </template>
        </a-input>
        <a-button @click.stop="getSubList" class="chaxun">查询</a-button>
      </span>
      <span class="oe-manage-btns">
        <!-- <a-button type="primary" @click.stop="getSubList">查询</a-button> -->
        <a-button v-show="isShow" @click="showModal" v-if="operationList.includes('add/edit/del')"
          >从职教云导入</a-button
        >
        <a-button @click="showAdd('add')" v-if="operationList.includes('add/edit/del')">新增</a-button>
        <a-button @click="importExcelQues" v-if="operationList.includes('add/edit/del')">Excel导入</a-button>
      </span>
   
    </div>
    <div class="oe-sub-contain">
      <a-modal
        :title="titleText"
        class="oe-studentAdd"
        :visible="add"
        :confirmLoading="confirmLoading"
        @cancel="addCancel"
      >
        <div class="oe-select">
          <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-model-item label="院系名称" prop="Name" ref="Name">
              <a-input v-model="form.Name" placeholder="请输入院系名称" />
            </a-form-model-item>
            <a-form-model-item label="院系编码" prop="Code" ref="Code">
              <a-input v-model="form.Code" placeholder="请输入院系编码" />
            </a-form-model-item>
            <a-form-model-item label="备注" prop="studentNum" ref="studentNum">
              <a-input v-model="form.studentNum" placeholder="请输入备注" />
            </a-form-model-item>
          </a-form-model>
        </div>
        <template slot="footer">
          <a-button @click="addSure" type="primary" html-type="submit">确定</a-button>
          <a-button @click.stop="addCancel">取消</a-button>
        </template>
      </a-modal>
      <a-modal
        title="从职教云导入"
        class="oe-student"
        :visible="imported"
        width="70%"
        @cancel="importedCancel"
        :afterClose="afterClose"
      >
        <div class="oe-select">
          <span class="oe-question-text">院系名称：</span>
          <span class="oe-select-input">
            <a-input placeholder="请输入院系名称/编码" v-model="keyZjy" />
          </span>
          <a-button type="primary" @click.stop="getZJYSubList">查询</a-button>
          <span class="oe-tips">【院系名称重复，将不会重复导入】</span>
        </div>
        <div class="oe-select-table">
          <a-table
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectSub }"
            :columns="importedColumns"
            :dataSource="importedDatas"
            :pagination="paginationZjy"
            @change="onZjyTableChange"
            :scroll="{ y: 240 }"
          ></a-table>
        </div>
        <template slot="footer">
          <a-button @click="importedSure" type="primary" html-type="submit">确定</a-button>
          <a-button @click.stop="importedCancel">取消</a-button>
        </template>
      </a-modal>
      <a-modal title="excel导入" class="oe-student" :visible="importExcel" width="40%" @cancel="importedCancelExcel">
        <div class="oe-select">
          <span class="oe-manage-select">
            <h2>注意事项：</h2>
            <div>1、导入excel前建议先查看下载模板中的示例，按要求添加导入信息</div>
            <div>2、请按照模板规范顺序导入数据,带"*"为必填项</div>
            <div>3、一次上传的数量请不要大于3000条</div>
          </span>
        </div>
        <div class="oe-select">
          <a href="/exam/excel/院系导入模板.xlsx">下载模板</a>
        </div>
        <div>
          <div class="clearfix">
            <a-upload :fileList="fileList" :remove="handleRemove" :beforeUpload="beforeUpload" accept=".xlsx">
              <a-button> <a-icon type="upload" />选择文件 </a-button>
            </a-upload>
          </div>
        </div>
        <div class="oe-select-table">
          <a-table
            :columns="errorColumns"
            :dataSource="errorList"
            :pagination="false"
            v-if="errorList.length > 0"
          ></a-table>
        </div>
        <template slot="footer">
          <a-button
            type="primary"
            v-if="!isContinue"
            @click="handleUpload(0)"
            :disabled="fileCount === 0"
            :loading="uploading"
            style="margin-top: 16px"
            >{{ uploading ? '上传中' : '上传' }}</a-button
          >
          <a-button
            type="primary"
            v-if="isContinue"
            @click="handleUpload(1)"
            :disabled="fileCount === 0"
            :loading="uploading"
            style="margin-top: 16px"
            >{{ uploading ? '上传中' : '继续上传' }}</a-button
          >
          <a-button @click.stop="importedCancelExcel">取消</a-button>
        </template>
      </a-modal>
      <div class="oe-manage-content">
        <a-table
          :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectData }"
          :columns="columns"
          :dataSource="datas"
          :pagination="pagination"
          @change="onTableChange"
        >
          <span slot="action" slot-scope="text, record">
            <a-tooltip placement="bottom" title="编辑" v-if="operationList.includes('add/edit/del')" class="bianji">
              <span @click="showAdd(record)" class="action-icon">
                <i class="iconfont icon-edit"></i>
                <span>编辑</span>
              </span>
            </a-tooltip>
            <a-tooltip placement="bottom" title="删除" v-if="operationList.includes('add/edit/del')">
              <span @click="deleted(record)" class="action-icon">
                <i class="iconfont icon-delete"></i>
                <span>删除</span>
              </span>
            </a-tooltip>
          </span>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  mixins: [GetOperationList],
  components: {
    topTip,
  },
  data() {
    return {
      titleText: '',
      title: [{ text: '院系管理' }],
      key: '',
      keyZjy: '',
      idsSubs: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      //新增
      add: false,
      //是否展示从职教云导入
      isShow: false,
      form: {
        Name: '',
        Code: '',
        studentNum: '',
      },
      rules: {
        Name: [
          { required: true, message: '请输入院系名称！', trigger: 'blur' },
          { min: 1, max: 20, message: '请输入1-20个字符', trigger: 'blur' },
        ],
        Code: [
          { required: true, message: '请输入院系编码！', trigger: 'blur' },
          { min: 1, max: 20, message: '请输入1-20个字符', trigger: 'blur' },
        ],
      },
      //导入
      imported: false,
      importedColumns: [
        {
          title: '序号',
          dataIndex: 'Number',
          align: 'center',
        },
        {
          title: '院系名称',
          dataIndex: 'Name',
          sorter: true,
          align: 'center',
        },
        {
          title: '院系编码',
          dataIndex: 'Code',
          sorter: true,
          align: 'center',
        },
      ],
      columns: [
        {
          title: '序号',
          dataIndex: 'Number',
          align: 'center',
        },
        {
          title: '院系名称',
          dataIndex: 'Name',
          sorter: true,
          align: 'center',
        },
        {
          title: '院系编码',
          dataIndex: 'Code',
          sorter: true,
          align: 'center',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
        },
      ],
      importedDatas: [],
      //
      selectType: '', //选择的类型
      selectedRowKeys: [],
      datas: [],
      // 分页配置
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          // this.getExamList(current, pageSize);
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0,
      },
      //弹框分页配置
      paginationZjy: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showQuickJumper: false,
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.paginationZjy.current = current;
          this.paginationZjy.pageSize = pageSize;
        },
        onChange: (current, pageSize) => {
          this.paginationZjy.current = current;
          this.paginationZjy.pageSize = pageSize;
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10,
        total: 0,
      },
      // 操作List
      operationList: [],
      IsOpList: [],
      loading: false,
      lock: false,
      importExcel: false,
      fileList: [],
      fileCount: 0,
      errorList: [],
      errorColumns: [
        {
          title: '序号',
          dataIndex: 'Number',
          align: 'center',
        },
        {
          title: '明细',
          dataIndex: 'Title',
          align: 'center',
        },
      ],
      uploading: false,
      isContinue: false,
      rowList: [],
    };
  },
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0;
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getOpeartion();
    });
  },
  methods: {
    // 判断是否是只读
    getIsWrite(type) {
      type = 'add/edit/del';
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    // 点击table排序
    onTableChange(pagenation, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getSubList(pagenation.current, pagenation.pageSize, sortOrder);
    },
    // 获取页面操作
    getOpeartion() {
      this.loading = true;
      this.GetOperationList().then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if (item.IsWrite) {
                this.operationList.push(item.Name);
              }
              this.IsOpList = rst.list;
            });
          }
          this.getSubList();
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    //获取院系列表
    getSubList(page, pageSize, sortOrder) {
      this.loading = true;
      this.$http
        .post('/api/SchoolManager/SubInfo/getSubList', {
          key: this.key,
          sort: sortOrder || '',
          page: page || 1,
          pageSize: pageSize || 10,
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code > 0) {
            if (rst.isZjySchool) {
              this.isShow = true;
            }
            this.datas = [];
            this.pagination.current = rst.pagination.pageIndex;
            this.pagination.pageSize = rst.pagination.pageSize;
            this.pagination.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.datas.push({
                  ...item,
                  Number: number,
                });
              });
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    //新增
    showAdd(value) {
      if (value == 'add') {
        if (!this.getIsWrite('新增')) {
          return;
        }
        this.titleText = '新增信息';
        // this.form.Name = '';
        // this.form.Code = '';
        // this.form.studentNum = '';
        console.log('xinze');
      } else {
        if (!this.getIsWrite('编辑')) {
          return;
        }
        this.lookItem = value;
        this.titleText = '编辑信息';
        console.log('edit');
        this.loading = true;
        this.$http
          .post('/api/SchoolManager/subInfo/editInfo', {
            id: value.Id,
          })
          .then((res) => {
            this.loading = false;
            this.form.Name = res.info.Name;
            this.form.Code = res.info.Code;
            this.form.studentNum = String(res.info.Remark);
          });
      }
      this.add = true;
    },
    addCancel() {
      this.add = false;
      this.$refs.ruleForm.resetFields();
    },
    // 职教云导入modal关闭的回调
    afterClose() {
      this.idsSubs = [];
      this.selectedRowKeys = [];
      this.keyZjy = '';
    },
    addSure() {
      let id = this.titleText === '编辑信息' ? this.lookItem.Id : '';
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$http
            .post('/api/SchoolManager/SubInfo/saveInfo', {
              id: id,
              name: this.form.Name,
              code: this.form.Code,
              remark: this.form.studentNum,
            })
            .then((rst) => {
              this.loading = false;
              this.lookItem = '';
              if (rst.code === 1) {
                //let msg = this.titleText === '编辑信息' ? '修改成功' : '新增成功';
                this.$message.success(rst.msg);
                this.form = {
                  Name: '',
                  Code: '',
                  studentNum: '',
                };
                this.getSubList();
                this.add = false;
              } else {
                this.$message.error(rst.msg);
              }
            });
        } else {
          return false;
        }
      });
    },
    //删除
    deleted(value) {
      if (!this.getIsWrite('删除')) {
        return;
      }
      this.$confirm({
        title: '提示',
        content: '确认删除选择的数据吗？',
        centered: true,
        onOk: () => {
          this.$http
            .post('/api/SchoolManager/subInfo/deleteSub', {
              id: value.Id, //要删除的成员id数组
            })
            .then((res) => {
              if (res.code > 0) {
                this.$message.success(res.msg);
                this.getSubList();
              } else {
                this.$message.error(res.msg);
              }
            });
        },
        onCancel() {},
      });
    },
    //导入
    showModal() {
      this.imported = true;
      this.getZJYSubList();
    },
    // 点击table排序
    onZjyTableChange(paginationZjy, filter, sort) {
      let sortOrder = '';
      if (sort.order) {
        if (sort.order == 'ascend') {
          sortOrder = sort.columnKey;
        } else if (sort.order == 'descend') {
          sortOrder = '-' + sort.columnKey;
        } else {
          sortOrder = '';
        }
      }
      this.getZJYSubList(paginationZjy.current, paginationZjy.pageSize, sortOrder);
    },
    getZJYSubList(page, pageSize, sortOrder) {
      this.loading = true;
      this.$http
        .post('/api/SchoolManager/SubInfo/getZJYSubList', {
          key: this.keyZjy,
          sort: sortOrder || '',
          page: page || 1,
          pageSize: pageSize || 10,
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code == 1) {
            this.idsSubs = [];
            this.selectedRowKeys = [];
            this.importedDatas = [];
            this.paginationZjy.current = rst.pagination.pageIndex;
            this.paginationZjy.pageSize = rst.pagination.pageSize;
            this.paginationZjy.total = rst.pagination.totalCount;
            if (rst.list.length) {
              rst.list.forEach((item, index) => {
                let number = (rst.pagination.pageIndex - 1) * rst.pagination.pageSize + index + 1;
                this.importedDatas.push({
                  ...item,
                  Number: number,
                });
                // console.log(this.datas);
              });
            }
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    importedCancel() {
      this.imported = false;
      this.keyZjy = '';
    },
    importedSure() {
      if (!this.getIsWrite('从职教云导入')) {
        return;
      }
      this.$http
        .post('/api/SchoolManager/SubInfo/importZJYSub', {
          ids: this.idsSubs,
        })
        .then((rst) => {
          this.loading = false;
          if (rst.code > 0) {
            this.idsSubs = [];
            this.selectedRowKeys = [];
            this.imported = false;
            this.$message.success(rst.msg);
            this.getSubList();
          } else {
            this.$message.error(rst.msg);
          }
        });
    },
    //多选
    onSelectSub(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      var ids = [];
      for (let i = 0; i < selectedRows.length; i++) {
        ids.push(selectedRows[i].Id);
      }
      this.idsSubs = ids;
    },
    importedCancelExcel() {
      this.importExcel = false;
      this.isContinue = false;
      this.rowList = [];
    },
    //点击excel导入
    importExcelQues() {
      if (!this.getIsWrite('新增')) {
        return;
      }
      this.fileCount = 0;
      this.errorList = [];
      this.fileList = [];
      this.importExcel = true;
      this.isContinue = false;
      this.rowList = [];
    },
    //删除文件
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.errorList = [];
      this.isContinue = false;
      this.rowList = [];
    },
    //选择文件
    beforeUpload(file) {
      this.fileList = [];
      this.fileCount = 1;
      this.fileList = [...this.fileList, file];
      this.isContinue = false;
      this.rowList = [];
      return false;
    },
    //上传
    handleUpload(type) {
      if (this.lock) {
        return;
      }
      var api = '/api/schoolManager/subInfo/importExcelSub';
      if (type == 1) {
        api = '/api/schoolManager/subInfo/continueImpSub';
      } else {
        this.rowList = [];
      }
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach((file) => {
        formData.append('files[]', file);
        formData.append('rowList', this.rowList);
      });
      this.lock = true;
      this.uploading = true;
      this.$http.post(api, formData).then((res) => {
        this.lock = false;
        this.errorList = [];
        this.uploading = false;
        if (res.code > 0) {
          this.fileCount = 0;
          this.importExcel = false;
          this.getSubList();
          this.$message.success(res.msg);
        } else if (res.code == -100) {
          this.isContinue = true;
          this.rowList = res.rowList;
          this.$message.error(res.msg);
          // this.errorList = res.list;
          if (res.list.length) {
            res.list.forEach((item, index) => {
              this.errorList.push({
                Title: item,
                Number: index + 1,
              });
              // console.log(this.datas);
            });
          }
        } else {
          this.$message.error(res.msg);
          this.fileCount = 0;
        }
      });
    },
  },
};
</script>
